<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Contracts\Index\SearchContracts;
use App\Models\Users;
use Tymon\JWTAuth\Facades\JWTAuth;
// 请求验证类

class IndexController extends Controller
{
	public $usermodel;
	public function __construct()
	{
		$this->usermodel = new Users();
	}
	public function login_test(Request $request)
	{
		$input = $request->only('name','password');

		$jwt_token = '';
		if(!$jwt_token = JWTAuth::attempt($input)){
			return response()->json([
				'success'=>false,
				'message'=>'invalid name or password'
			],401);
		}

		return response()->json([
			'success'=> true,
			'token'=>$jwt_token
		]);
	}

	// 获取用户信息
	public function get_user()
	{
		//A token is required啊
		$user = JWTAuth::parseToken()->touser();//自带token必需验证

		return response()->json([
			'success'=> true,
			'data'=>$user
		]);
	}

	// 产品列表
	public function store(Request $request,SearchContracts $searchContracts)
	{
        if($request->post('search')){
            $searchContracts->search($request->post('search'));
        }

		if($request->post('orderby')){
            $searchContracts->orderby($request->post('orderby'));
        }
		if($request->token){
			$user = JWTAuth::parseToken()->touser();//自带token必需验证
		}
		$list = $searchContracts->getproduct();

		//是否已收藏
		foreach($list as $k=>$v){
			if($request->token){
				if(!$user->favoriteProducts()->find($v->id)){
					$list[$k]['is_favor'] = 0;
				}else{
					$list[$k]['is_favor'] = 1;
				}
			}else{
				$list[$k]['is_favor'] = 0;
			}
			
		}
		return $this->response($list);
	}

}
